<!-- 编辑弹窗 -->
<template>
    <ele-modal
      inner
      fullscreen
      :movable="false"
      :visible="visible"
      :close-on-click-modal="true"
      :before-close="handleClose"
      custom-class="ele-dialog-form"
      :title="isUpdate ? '修改销售订单' : '添加销售订单'"
      @update:visible="updateVisible" 
    >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
      <el-card  >  
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 50%;" >基础信息</div>
          <div style="width: 50%;display: flex;justify-content:end;" >
            <div  v-show="form.status>=0" style="width: 30%;color:var(--color-primary)" >销售订单号:{{ form.orderNo }}</div>
          </div>
        </div>      
        <el-row :gutter="24">
          <el-col :md="6" :sm="24">
            <el-form-item label="客户名称:" prop="customerId">
              <el-select  v-model="form.customerId" filterable clearable placeholder="请选择客户" style="width:100%" >
                <el-option  v-for="item in customerDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="交货日期:"  prop="deliveryDate">
              <el-date-picker v-model="form.deliveryDate" type="date" placeholder="请输入交货日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%"  />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="制单日期:"  prop="orderDate">
              <el-date-picker v-model="form.orderDate" type="date" placeholder="请输入制单日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%"  />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="制单人:" prop="operatorId">
              <el-select  v-model="form.operatorId" filterable placeholder="请选择制单人" style="width:100%" >
                <el-option  v-for="item in accountDatas" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="币种:" prop="currencyId">
              <el-select  v-model="form.currencyId" filterable placeholder="请选择币种" style="width:100%" @change="changeCurrencyRate" >
                <el-option  v-for="item in currencyDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="汇率:" prop="rate">
              <el-input v-model="form.rate" placeholder="请输入汇率"  @change="setRate" />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="发货仓库:" prop="warehouseId">
              <el-select  v-model="form.warehouseId" filterable clearable placeholder="请选择发货仓库" style="width:100%" >
                <el-option v-for="item in wareHouseDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="收款账户:" prop="bankAccountId">
              <el-select  v-model="form.bankAccountId" filterable clearable placeholder="请选择收款账户" style="width:100%"  @change="changeBank" >
                <el-option v-for="item in bankAccountDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="产品数量:" >
              <el-input v-model="form.qtyTotal" disabled />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="提成金额:" >
              <el-input v-model="form.commissionAmountTotal" disabled />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="提成金额"  >
              <el-input v-model="form.commissionAmountCnTotal"  prefix-icon="el-icon-_rmb"  disabled />
            </el-form-item>
          </el-col>
          <el-col :md="24" :sm="24" >
            <el-form-item label="备注:"  >
              <el-input :rows="2"
                  clearable
                  type="textarea"
                  :maxlength="200"
                  v-model="form.remark"
                  placeholder="请输入备注说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card  style="margin-top: 10px">
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 50%;" >产品列表</div>
          <div style="width: 50%;display: flex;justify-content:end;" >
            <div style="width: 30%;color:var(--color-primary)" > 
                <el-button icon="el-icon-plus" style="width: 100%;" @click="OpenProductList"  >选择产品 </el-button>
              </div>
          </div>
        </div> 
        <el-table :data="form.items" ref="items"  :border="true" style="width: 100%" :height="tableHeight" :full-height="tableFullHeight" >
          <el-table-column type="index" width="50" align="center" label="序号" fixed='left' />
          <el-table-column label="产品编号"   align="center"  width="150">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <span>{{ row.productCode }}</span>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="产品名称"   align="center"  width="150">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <span>{{ row.productName }}</span>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="规格" align="center"   width="100">
            <template slot-scope="{ row }">
              <span>{{ row.spc }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center"  width="80">
              <template slot-scope="{ row }">
                <span>{{ row.unitDesc }}</span>
              </template>
          </el-table-column>
          <el-table-column label="数量" align="center"  width="100">
            <template slot-scope="{row,$index}">
              <el-form-item label-width="10" style="margin-bottom:0;" :prop="'items.'+ $index+'.qty'" :rules="itemRules.qty" >
                <el-input  v-model="row.qty"  placeholder="请输入数量" @change="setAmount(row,$index)"  @keyup.native="row.qty = row.qty.replace(/[^\d.]/g,'');
                  row.qty = row.qty.replace(/\.{2,}/g,'.');
                  row.qty = row.qty.replace(/^\./g,'');
                  row.qty = row.qty.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  row.qty = row.qty.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="剩余发货数量" align="center"  width="140">
            <template slot-scope="{ row }">
              <span>{{ row.surplusDeliveryQty }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center"  width="120">
              <template slot-scope="{row,$index}">
                <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'items.'+ $index+'.price'" :rules="itemRules.price">
                  <el-input  v-model="row.price"  placeholder="请输入单价"  @change="setAmount(row,$index)" @keyup.native="row.price = row.price.replace(/[^\d.]/g,'');
                  row.price = row.price.replace(/\.{2,}/g,'.');
                  row.price = row.price.replace(/^\./g,'');
                  row.price = row.price.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  row.price = row.price.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');" />
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="金额" align="center"  width="140">
            <template slot-scope="{ row }">
              <span>{{ row.amount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单价(￥)" align="center"  width="120">
            <template slot-scope="{ row }">
              <span>{{ row.priceCn }}</span>
            </template>
          </el-table-column>
          <el-table-column label="金额(￥)" align="center"  width="140">
            <template slot-scope="{ row }">
              <span>{{ row.amountCn }}</span>
            </template>
          </el-table-column>
          <el-table-column label="发货仓库" align="center" width="150" >
            <template slot-scope="{ row ,$index }">
              <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'items.'+ $index+'.deliveryWareHouseId'" :rules="itemRules.deliveryWareHouseId">
                <el-select  filterable v-model="row.deliveryWareHouseId" placeholder="请选择发货仓库" class="ele-fluid" >
                  <el-option v-for="item in wareHouseDatas" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="提成类型" align="center" width="150" >
            <template slot-scope="{ row }">
              <el-form-item label-width="10" style="margin-bottom:0;" >
                <!-- <el-select  filterable clearable v-model="row.commissionType" placeholder="请选择提成类型" class="ele-fluid" @change="changeCommissionType(row)" @clear="clear(row)">
                  <el-option v-for="(item, index) in commissionTypeDatas" :key="index" :label="item.Value" :value="item.Key" />
                </el-select> -->
                <span>{{ row.commissionName }}</span>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column label="提成规则" align="center"  width="200">
            <template slot-scope="{ row }">
              <span>{{ row.rules }}</span>
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="提成方案" align="center" width="150" >
            <template slot-scope="{ row }">
              <el-form-item label-width="10" style="margin-bottom:0;"   >
                <el-select  filterable clearable disabled v-model="row.commissionId" placeholder="请选择提成方案" class="ele-fluid" >
                  <el-option v-for="item in commissionDatas" :key="item.id" :label="item.rules" :value="item.id" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="提成类型" align="center"  width="100">
            <template slot-scope="{ row }">
              <span>{{ row.commissionName }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="提成比例(%)" align="center"  width="100">
            <template slot-scope="{ row }">
              <span>{{ row.scale?row.scale:'无' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="提成金额" align="center"  width="120" >
            <template slot-scope="{ row }">
              <span>{{ row.commissionAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="提成金额(￥)" align="center"  width="120">
            <template slot-scope="{ row }">
              <span>{{ row.commissionAmountCn }}</span>
            </template>
          </el-table-column>
          <el-table-column label="行备注" align="center" width="150">
            <template slot-scope="{ row }">
              <el-input  v-model="row.remarks" placeholder="请输入行备注" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center"  width="80" :resizable="false" v-if="this.btnIndex!=3" fixed='right' >
            <template slot-scope="{ row , $index}">
              <span class="ele-action">
                <el-link  icon="el-icon-delete" type="danger" :underline="false" @click="remove(row, $index)" >删除</el-link>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card shadow="never"> 
      </el-card>
    </el-form>
    <div slot="footer">
      <div class="ele-dailog-bottom">
        <div class="left" style="display: flex;width: 50%;">
              <div ><span>订单金额：<span class="moneycolor moneyxh">{{ form.orderAmount }}</span>
                  优惠金额：</span>
                  <el-input  v-model="form.disAmount"  placeholder="请输入优惠金额" @change="setRecAmount"   style="width:100px" @keyup.native="form.disAmount = form.disAmount.replace(/[^\d.]/g,'');
                          form.disAmount = form.disAmount.replace(/\.{2,}/g,'.');
                          form.disAmount = form.disAmount.replace(/^\./g,'');
                          form.disAmount = form.disAmount.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                          form.disAmount = form.disAmount.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');" ></el-input>  
                  <span v-show="this.form.status==15" class="moneycolor moneyxh">{{ form.disAmount }}</span>
                </div>
                <div >
                  收款金额：<el-input  v-model="form.recAmount"  placeholder="请输入收款金额" @change="checkAmount" @blur="checkAmount"  style="width:100px" @keyup.native="form.recAmount = form.recAmount.replace(/[^\d.]/g,'');
                          form.recAmount = form.recAmount.replace(/\.{2,}/g,'.');
                          form.recAmount = form.recAmount.replace(/^\./g,'');
                          form.recAmount = form.recAmount.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                          form.recAmount = form.recAmount.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');" ></el-input>  
            </div>
        </div>
        <div class="right" style="display: flex;width: 32%;">
          <el-button type="primary" v-show="this.btnIndex!=3 &&  form.status!=5"  @click="save">挂单</el-button>
          <el-button type="info" @click="print"  v-show="form.status>=0">打印</el-button>
          <el-button  @click="handleClose">关闭</el-button>
        </div>
      </div>
    </div>
     <!-- 编辑弹窗 -->
     <productList :visible.sync="showProductList"  @callback="reloadItemList"/>
    </ele-modal>
  </template>
  <script>
   import { printHtml } from 'ele-admin';
   import productList from './product-list.vue';
   import { getUser } from '@/utils/user-util';
   import upload from "@/components/UpLoad/index.js";
   import { GetAllAccount } from '@/api/usermanager/accountmanager';
   import { GetAllBackAccount } from '@/api/basicdatamanager/bankaccount';
   import { QueryCustomerPageList } from '@/api/basicdatamanager/customer';
   import { GetAllWarehouse } from '@/api/basicdatamanager/warehousemanager';
   import { QueryAllChildDictViewByCode } from '@/api/systemmanager/dictmanager';
   import { QueryModelBycurrencyId } from '@/api/basicdatamanager/ratemanager';
   import { GetAllBSupplier} from '@/api/basicdatamanager/supplier';
   import { QueryCommissionTypeEnum} from '@/api/enummanger';
   import { AddSaleorder, UpdateSaleorder,QuerySaleorderById,PrintSaleOrderById} from '@/api/businesshandling/saleordermanager';
   import { QueryCommissionPageList,QueryCommissionByProductTypeId,QueryCommissionBySaleQty} from '@/api/basicdatamanager/commissionplan';


    export default {
      name: 'SaleOrderEditCom',
      props: {
        // 弹窗是否打开
        visible: Boolean,
        // 修改回显的数据
        data: Object,
        // 按钮索引
        btnIndex:String,
      },
      mixins: [upload],
      components: {productList},
      data() {
        return {
          // 表单数据
          form: {operatorId:'',orderDate:'',orderAmount:0,disAmount:0,recAmount:0},
          fixedHeight:true,
          // 表单验证规则
          rules: {
            customerId: [{required: true,message: '请选择客户',trigger: 'blur'}],
            deliveryDate: [{required: true,message: '请输入交货日期',trigger: 'blur'}],
            currencyId: [{required: true,message: '请选择币种',trigger: 'blur'}],
            rate: [{required: true,message: '请输入汇率',trigger: 'blur'}],
            warehouseId: [{required: true,message: '请输入发货仓库',trigger: 'blur'}],
            orderDate: [{required: true,message: '请输入制单日期',trigger: 'blur'}],
            bankAccountId:[{required: true,message: '请选择收款账户',trigger: 'blur'}],
          },
          itemRules: {
            qty: [{required: true,message: '请输入数量',trigger: 'blur'}],
            price: [{required: true,message: '请输入单价',trigger: 'blur'}],
            commissionId:[{required: true,message: '请选择提成方案',trigger: 'blur'}],
            deliveryWareHouseId: [{required: true,message: '请输入发货仓库',trigger: 'blur'}],
          },
         
          isShow:false,
          // 提交状态
          loading: false,
          // 是否是修改
          isUpdate: false,
          showProductList:false,
          defaultDate:new Date(),
          accountDatas:[],
          currencyDatas:[],
          wareHouseDatas:[],
          customerDatas:[],
          commissionDatas:[],
          commissionTypeDatas:[],
          bankAccountDatas:[],
          RMB:'',
        };
      },
      computed: {
        // 表格高度
        tableHeight() {
          var fh = this.fixedHeight ? 'calc(100vh - 350px)' : void 0;

          return fh;
        },
        // 表格全屏时高度
        tableFullHeight() {
          var fh =  this.fixedHeight ? 'calc(100vh - 280px)' : null;

          return fh;
        },
      },
      //初始化数据
      mounted(){
        this.initData();
      },
      methods: {

        /* 初始化数据 */
        async initData(){

          GetAllAccount().then((res)=>{
            this.accountDatas = [];
            this.accountDatas = res;
          });

          GetAllBSupplier().then((res)=>{
            this.supplierDatas = [];
            this.supplierDatas = res;
          });

          GetAllWarehouse().then((res)=>{
            this.wareHouseDatas = [];
            this.wareHouseDatas = res;
          });

          GetAllBackAccount().then((res)=>{
            this.bankAccountDatas = [];
            this.bankAccountDatas = res;
          });

          QueryCommissionTypeEnum().then((res)=>{
            res.map(e=>{
              this.commissionTypeDatas.push({Key:e.Key,Value:e.Value});
            });
          });

          QueryAllChildDictViewByCode(this.Constant.C_HB).then((res)=>{
            this.currencyDatas = [];
            this.currencyDatas = res;

            let hb = res.find((m)=>{return m.code == 'C-HB01'});
            if(hb)this.RMB = hb.id;
          });

          let params = {
              pageindex: 1,
              pagesize: 100000,
              conditions: [],
              orderBys: [{ sort: "createDate", order: 1, }],
            };


          params.conditions.push({
            key:"deleted",
            operator: 0,
            value: 0,
          });

          let result = await QueryCustomerPageList(params);
          this.customerDatas=[];
          this.customerDatas = result.items;


          let commissions = await QueryCommissionPageList(params);
          this.commissionDatas=[];
          this.commissionDatas = commissions.items;
        },


        /* 保存编辑 */
        save() {
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}

            if(!this.form.recAmount){
              this.$message.error('收款金额不能为空');
              return;
            }

            if(parseFloat(this.form.recAmount)<=0){
              this.$message.error('收款金额不能小于等于零');
              return;
            }

            let totalamount = parseFloat(this.form.disAmount?this.form.disAmount:0)  + parseFloat(this.form.recAmount?this.form.recAmount:0);
            let oamount = parseFloat(this.form.orderAmount)
            if( totalamount > oamount){
              this.$message.info("收款金额+优惠金额不能大于订单金额");
              // this.form.recAmount = 0;
              return;
            }

            this.loading = true;
            const saveOrUpdate = this.isUpdate ? UpdateSaleorder : AddSaleorder;
            saveOrUpdate(this.form)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible(false);
              //回调父组件方法
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
          });
        },

        setData(id){
          QuerySaleorderById(id)
            .then((res) => {
              this.form = res; 

              this.$nextTick(() => {
                this.$refs.items.doLayout();
              });
          });
        },

        OpenProductList(){
          this.showProductList =true;
        },

        reloadItemList(orderData){

          if(this.form.items==null || this.form.items ==undefined){
            this.form.items = [];
          }

          orderData.map((item)=>{

            let product = this.form.items.find((d)=>{
              return d.productId == item.id && d.deliveryWareHouseId == item.wareHouseId
            })
            if(product){
              this.$message.info('当前选择的产品'+product.productName+'在列表中已经存在');
              return;
            }else{
              this.form.items.push({
                orderId:this.form.id,
                productId:item.id,
                qty:0,
                price:0,
                unitId:item.unitId,
                amount:0,
                rate:this.form.rate,
                currencyId:this.form.currencyId,
                priceCn:0,
                amountCn:0,
                deliveryQty:0,
                deliveryWareHouseId:item.wareHouseId?item.wareHouseId:this.form.warehouseId,
                commissionId:'',
                commissionType:null,
                commissionName:'',
                scale:0,
                commissionAmount:0,
                commissionAmountCn:0,
                costPrice:item.purPrice,
                productCode:item.code,
                productName:item.name,
                productTypeId:item.typeId,
                spc:item.spc,
                unitDesc:item.unitDesc,
                remarks:item.remarks,
              })
            }
          });

          this.$nextTick(() => {
            this.$refs.items.doLayout();
          });
        },

        //设置金额
        setAmount(row,index){
          if(row.price && row.qty){
              let q = parseFloat(row.qty);
              let p = parseFloat(row.price);
              this.$refs.items.data[index].amount = (p * q).toFixed(4);
          }

          if(row.amount && this.form.rate){
              let r = parseFloat(this.form.rate);
              let a = parseFloat(row.amount);
              this.$refs.items.data[index].amountCn = (a / r).toFixed(4);
          }

          if(row.amountCn && row.qty){
              let rq = parseFloat(row.qty);
              let ra = parseFloat(row.amountCn);
              this.$refs.items.data[index].priceCn = (ra / rq).toFixed(4);
          }

          if(row.amount && row.scale){
              let s = parseFloat(row.scale);
              let a = parseFloat(row.amount);
              this.$refs.items.data[index].commissionAmount = ((s * a)/100).toFixed(4);
          }

          if(row.commissionAmount && this.form.rate){
              this.$refs.items.data[index].commissionAmountCn = (row.commissionAmount/this.form.rate).toFixed(4);
          }
          
          /*剩余发货数 =  销售数量*/
          this.$refs.items.data[index].surplusDeliveryQty = row.qty;
          this.setCommissionAmountTotal();
          // this.setRate();

          this.changeCommissionType(row);
        },

        //汇率发生变化时,对应产品明细的相关数据发生变化
        setRate(){

          this.$refs.items.data.map((item)=>{

            item.amount = (item.price && item.qty)?(item.qty * item.price).toFixed(4):0;
            item.amountCn = (item.amount && this.form.rate )?(item.amount / parseFloat(this.form.rate)).toFixed(4):0;
            item.priceCn = (item.amountCn && item.qty)?(item.amountCn / item.qty).toFixed(4):0;
            item.commissionAmount = (item.amount && item.scale)?((item.amount * item.scale)/100).toFixed(4):0;
            item.commissionAmountCn = ((item.commissionAmount)/parseFloat(this.form.rate)).toFixed(4);
          })

          this.setCommissionAmountTotal();
        },

        /* 删除 */
        remove(_row, index) {
          this.form.items.splice(index, 1);
          this.setCommissionAmountTotal();
        },

        // 选择提成方案
        changeCommission(row){
          let commission = this.commissionDatas.find((d)=>{
            return d.id == row.commissionId
          });

          if(commission){
            row.commissionAmount = 0;
            row.commissionAmountCn = 0;
            row.scale = commission.scale;
            row.commissionType = commission.code;
            row.commissionName = commission.commissionName;
            if(row.amount && row.scale){
              row.commissionAmount = (row.amount && row.scale)?((row.amount * row.scale)/100).toFixed(4):0;
              row.commissionAmountCn = ((row.commissionAmount)/parseFloat(this.form.rate)).toFixed(4);
            }
          }

          this.setCommissionAmountTotal();
        },

        // 选择提成类型
        changeCommissionType(row){
          if(row.commissionType===0 || row.commissionType===1 ){
            let commissionType = this.commissionTypeDatas.find((d)=>{
              return d.Key == row.commissionType
            });
            // 按产品类型提成
            if(commissionType){
              row.rules = '';
              row.commissionId = '';
              row.scale = null;
              row.commissionAmount = 0;
              row.commissionAmountCn = 0;
              
              if(row.commissionType == 0 && row.productTypeId){
                QueryCommissionByProductTypeId(row.productTypeId).then((res)=>{
                  if(res.code == 200){
                    row.rules = res.data.rules;
                    row.commissionId = res.data.id;
                    row.scale = res.data.scale;
                    row.productTypeId = res.data.productTypeId;
                  }
                  this.calculateCommissionAmount(row);
                });
              }

              // 按销售数量提成 
              if(row.commissionType == 1 && row.qty>0){

                row.rules = '';
                row.scale = null;
                row.commissionId = '';
                row.commissionAmount = 0;
                row.commissionAmountCn = 0;

                QueryCommissionBySaleQty(row.qty).then((res)=>{
                  if(res.code == 200){
                    row.rules = res.data.rules;
                    row.scale = res.data.scale;
                    row.commissionId = res.data.id;
                  }

                  this.calculateCommissionAmount(row);
                });
              }
            }
          }
        },

        // 清除提成类型
        clear(row){
          row.rules = '';
          row.commissionId = '';
          row.commissionType = '';
          row.scale = null;
          row.commissionAmount = 0;
          row.commissionAmountCn = 0;
        },

        //计算提成金额
        calculateCommissionAmount(row){

          row.commissionAmount = 0;
          row.commissionAmountCn = 0;
          if(row.amount && row.scale){
              row.commissionAmount = (row.amount && row.scale)?((row.amount * row.scale)/100).toFixed(4):0;
              row.commissionAmountCn = ((row.commissionAmount)/parseFloat(this.form.rate)).toFixed(4);
            }

            this.setCommissionAmountTotal();

        },

        //设置提成金额汇总
        setCommissionAmountTotal(){
          this.form.qtyTotal = 0;
          this.form.recAmount = 0;
          this.form.recAmountCn = 0;
          this.form.disAmount = 0;
          this.form.disAmountCn = 0;
          this.form.orderAmount = 0;
          this.form.orderAmountCn = 0;
          this.form.commissionAmountTotal = 0;
          this.form.commissionAmountCnTotal = 0;

          if(this.form.items!=null && this.form.items!=undefined && this.form.items.length>0){
            this.form.qtyTotal = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.qty)  },0);
            this.form.orderAmount = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.amount)  },0);
            this.form.commissionAmountTotal = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.commissionAmount?cur.commissionAmount:0)  },0);
            this.form.commissionAmountCnTotal = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.commissionAmountCn?cur.commissionAmountCn:0)  },0);
           
            this.form.qtyTotal =this.form.qtyTotal.toFixed(2);
            this.form.orderAmount = this.form.orderAmount.toFixed(4);
            this.form.commissionAmountTotal = this.form.commissionAmountTotal.toFixed(4);
            this.form.commissionAmountCnTotal = this.form.commissionAmountCnTotal.toFixed(4);

            this.form.orderAmountCn = (this.form.orderAmount/this.form.rate).toFixed(4);

            this.setRecAmount();
          }
        },

        setRecAmount(){
          // this.form.recAmount = (this.form.orderAmount - this.form.disAmount).toFixed(4);
          this.form.recAmountCn = (this.form.recAmount / this.form.rate).toFixed(4);
          if(this.form.disAmount){
            this.form.disAmountCn = (this.form.disAmount/this.form.rate).toFixed(4);
          }
          this.checkAmount();
          
        },

        checkAmount(){

          let totalamount = parseFloat(this.form.disAmount?this.form.disAmount:0) + parseFloat(this.form.recAmount?this.form.recAmount:0) ;
          let oamount = parseFloat(this.form.orderAmount?this.form.orderAmount:0);
          if( totalamount > oamount){
            this.$message.info("收款金额+优惠金额不能大于订单金额");
            // this.form.recAmount=0;
            return;
          }
        },

        changeBank(val){
          let bank = this.bankAccountDatas.find((b)=>{ return b.id == val});
          if(bank){
            this.form.bankAccount = bank.name;
          }
        },

        //设置币种
        setDefaultCurreny(){
          // C-HB03
          QueryAllChildDictViewByCode(this.Constant.C_HB).then((d)=>{

            d.map((item)=>{
              if(item.code == 'C-HB03'){
              this.form.currencyId = item.id;
              this.changeCurrencyRate(item.id);
            }
            })
          });
        },

        /* 更新visible */
        updateVisible(value) {
          //更新父组件中的visible的值
          this.$emit('update:visible', value);
        },

        handleClose() {
          this.$emit('update:visible', false);
        },

         /* 选择币种 */
       async changeCurrencyRate(val){

          let result = await QueryModelBycurrencyId(val);
          this.$set(this.form,'rate',result?result.rate:1);

          this.setRate();
        },

        // 打印
        print(){
          PrintSaleOrderById(this.form.id).then((data)=>{
            const pWindow = printHtml({
                html: data, // 要打印的内容
                // style: '<style>span { color: red; }</style>',  // 页面样式
                // title: '', // 页面标题，浏览器打印设置显示页眉会显示页面标题
                horizontal: true, // 是否横向打印
                blank: true, // 是否打开新页面打印
                close: true, // 如果是打开新页面，打印完是否关闭
                print: true, // 如果是打开新窗口是否自动打印
                iePreview: true, // 是否兼容 ie 打印预览
                loading: true, // 是否显示 loading
                before: () => { // 打印开始的回调
                },
                done: () => { // 打印完成的回调
                },
                margin: 0, // 页间距
                header: '', // 页眉 html
                footer: '' // 页脚 html
            });
          });
        },
    },
     
      /* 监听visible属性变化 */
      watch: {
        visible(visible) {
         
          if (visible) {
            if (this.data && this.data.id) {
              //赋值this.form
              this.setData(this.data.id);
              this.isUpdate = this.data.id !=null && this.data.id !=undefined;
            } else {
              this.form={operatorId:'',orderDate:'',orderAmount:0,disAmount:0,recAmount:0};
              this.isUpdate = false;
              let currentUser = getUser();
              this.$set(this.form,'orderDate',this.defaultDate);
              this.$set(this.form,'operatorId',currentUser.accountId);
              this.$set(this.form,'operatorName',currentUser.accountName);
              this.setDefaultCurreny();
            }
          } else {
              this.$refs['form'].clearValidate();
              this.form = {operatorId:'',orderDate:'',orderAmount:0,disAmount:0,recAmount:0};
              let currentUser = getUser();
              this.$set(this.form,'orderDate',this.defaultDate);
              this.$set(this.form,'operatorId',currentUser.accountId);
              this.$set(this.form,'operatorName',currentUser.accountName);
              this.setDefaultCurreny();
          }
        }
      }
    };
  </script>
  <style lang='scss' scoped>
   .hangs_two {
    width: 70%;
    color: chocolate;
    cursor: pointer;
    .text {
      text-decoration: underline;
      margin-right: 4px;
    }
    .iconfont {
      margin-right: 4px;
    }
  }
</style>